﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Reflection;
using System.Threading;
using System.Data.SqlClient;

namespace Fares
{
    public partial class FaresSetupFrm : FrmCard
    {
        public FaresSetupFrm(ModuleClass mInfo)
            : base(mInfo)
        {
            InitializeComponent();
            this.relationTextBox1.ButtonClick += new EventHandler(relationTextBox1_ButtonClick);
            this.relationTextBox2.ButtonClick += new EventHandler(relationTextBox1_ButtonClick);
            SerieNumericaBC.ButtonClick += new EventHandler(relationTextBox1_ButtonClick);
            SerieBF.ButtonClick += new EventHandler(relationTextBox1_ButtonClick);
            SerieAETB.ButtonClick += new EventHandler(relationTextBox1_ButtonClick);
            serieFACTTB.ButtonClick += new EventHandler(relationTextBox1_ButtonClick);
            serieCHITTB.ButtonClick += new EventHandler(relationTextBox1_ButtonClick);

            workConnString = mInfo.workConnectionString;
            eSRPDataSetSetup.FaresSetup.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            eSRPDataSetSetup.FaresSetup.PrimaryKeyColumn.DefaultValue = 0;
            eSRPDataSetSetup.FaresSetup.ParteneriPropriiColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.FolosesteAdresaColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.GolesteInainteImportColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.AnCurentColumn.DefaultValue = DateTime.Now.Year;
            eSRPDataSetSetup.FaresSetup.LunaCurentaColumn.DefaultValue = 1;
            eSRPDataSetSetup.FaresSetup.IDSerieColumn.DefaultValue = 0;
            eSRPDataSetSetup.FaresSetup.CotaTVAImplicitaColumn.DefaultValue = 24.0;
            eSRPDataSetSetup.FaresSetup.ComenziFaraTVAColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.AfiseazaProprietarDocumentColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.FaraCodArticolColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.FolosesteVarinataColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.FolosesteTermenLivrareColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.UtilizeazaDepartamentColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.CotaTVADetaliuDocumentColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.RegimFiscalDetaliuColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.FolosesteValoareCuAdaosColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.SalvareCuAdaugareColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.SalveazaCuUrmatorulNumarColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.AfiseazaDoarDocumenteleCurenteColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.FolosesteObservatiiColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.AfiseazaSemnaturiTiparireColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.IDSerieBCColumn.DefaultValue = 0;
            eSRPDataSetSetup.FaresSetup.IDSerieBFColumn.DefaultValue = 0;
            eSRPDataSetSetup.FaresSetup.GestiuneaStocurilorColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.BugetaraColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.ValutaColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.ValutaImplicitaColumn.DefaultValue = 0;
            eSRPDataSetSetup.FaresSetup.FolosesteTVAArticolColumn.DefaultValue = 0;
            eSRPDataSetSetup.FaresSetup.ProductieColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.ImplementareAmbalajeColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.AreDocGestStocColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.AvizExpeditieCuTVAColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.ComandaFaraPreturiColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.ProdusePePartenerColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.DenumireNumeric1Column.DefaultValue = "Lungime";
            eSRPDataSetSetup.FaresSetup.DenumireNumeric2Column.DefaultValue = "Latime";
            eSRPDataSetSetup.FaresSetup.DenumireNumeric3Column.DefaultValue = "Inaltime";
            eSRPDataSetSetup.FaresSetup.FolosesteContractColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.ZileScadentaClientColumn.DefaultValue = 15;
            eSRPDataSetSetup.FaresSetup.ZileScadentaFurnizorColumn.DefaultValue = 15;
            eSRPDataSetSetup.FaresSetup.TVAIncasareImplicitColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.PermiteTVALaIncasareColumn.DefaultValue = true;
            eSRPDataSetSetup.FaresSetup.GestiuneCantitativaColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.PermitePretZeroColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.FolosesteCPVColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.DataReceptieEgalaDataFacturaColumn.DefaultValue = false;
            eSRPDataSetSetup.FaresSetup.FolosesteDataExtrasColumn.DefaultValue = false;

        }

        void relationTextBox1_ButtonClick(object sender, EventArgs e)
        {
            FrmMainMdi frm = staticMdiParent as FrmMainMdi;
            if (frm == null)
                return;
            Assembly asm = frm.GetModule("erpforms");
            if (asm == null)
                return;
            String numeClasa = "ERPForms.SeriiNumericeRezumatFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                     new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;
                newFrm.SelectionAddOn = true;
                //newFrm.MdiParent = frm;
                if (newFrm.ShowDialog() == DialogResult.OK)
                {
                    //daca s-a selectat un rand se pune in text box valoare
                    ((RelationTextBox.RelationTextBox)sender).Text = newFrm.selectedRow.Cells["IdSerieColumn"].Value.ToString();
                }

            }
        }

        private void FaresSetupFrm_Load(object sender, EventArgs e)
        {
            try
            {
                SqlConnection con = DeschideConexiune(workConnString);
                banciTableAdapter.Connection = con;
                banciTableAdapter.Fill(eSRPDataSetSetup.Banci);
                this.faresSetupTableAdapter.Connection = con;
                this.tipDocumentTableAdapter.Connection = con;
                this.tipDocumentTableAdapter.FillByModificaStoc(this.eSRPDataSetSetup.TipDocument);
                this.valutaTableAdapter1.Connection = con;
                this.valutaTableAdapter1.Fill(this.eSRPDataSetSetup.Valuta);
                this.conturiTableAdapter1.Connection = con;
                this.conturiTableAdapter1.Fill(eSRPDataSetSetup.Conturi, ModuleInfo.CodUnitate);
                this.faresSetupTableAdapter.Fill(this.eSRPDataSetSetup.FaresSetup, ModuleInfo.CodUnitate);
                this.jurnaleTableAdapter.Connection = con;
                this.jurnaleTableAdapter.Fill(this.eSRPDataSetSetup.Jurnale,ModuleInfo.CodUnitate);
                this.articoleAliniateTableAdapter.Connection = con;
                this.articoleAliniateTableAdapter.FillByUnitate(this.eSRPDataSetSetup.ArticoleAliniate, ModuleInfo.CodUnitate);

                SqlCommand cmd = new SqlCommand("SELECT * FROM SeriiNumerice WHERE [CodUnitate]=" + ModuleInfo.CodUnitate,
                    con);

                SqlDataReader sdr = cmd.ExecuteReader();
                if (!sdr.HasRows)
                {
                    sdr.Close();
                    cmd.CommandText = "INSERT INTO [SeriiNumerice] ([IdSerie],[CodUnitate],[Descriere],[NrStart],[NumarImplicit],[NumarManual]) VALUES (" +
                        "'DOCSN'," + ModuleInfo.CodUnitate.ToString() + ",'Serie documente',1,1,1)";
                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "INSERT INTO [SeriiNumerice] ([IdSerie],[CodUnitate],[Descriere],[NrStart],[NumarImplicit],[NumarManual]) VALUES (" +
                        "'DOCPLSN'," + ModuleInfo.CodUnitate.ToString() + ",'Serie documente plata',1,1,1)";
                    cmd.ExecuteNonQuery();
                    eSRPDataSetSetup.FaresSetup.IDSerieColumn.DefaultValue = "DOCSN";
                    eSRPDataSetSetup.FaresSetup.IDSeriePlatiColumn.DefaultValue = "DOCPLSN";
                }
                else
                {
                    sdr.Close();
                }


                InchideConexiune(con);
            }
            catch(Exception ex)
            {
                TrateazaExceptie(ex);
                return;
            }
            
            this.listBndSourceMain.Add(faresSetupBindingSource);
            listTableAdaptor.Add(this.faresSetupTableAdapter.Adapter);

            if (faresSetupBindingSource.Count == 0)
            {
                faresSetupBindingSource.AllowNew = true;
                Adauga(this, null);
                faresSetupBindingSource.AllowNew = false;
                anCurentNUD.Enabled = true;
            }

            //AddButton("Inchidere An", global::ERPStudio.Properties.Resources._001_41, Inchidere_An, ToolStripItemAlignment.Right, false);
            
                
        }


        private void Inchidere_An(object sender, EventArgs e)
        {
            if (MessageBox.Show("Sunteti sigur ca doriti inchiderea anului curent(" + ((DataRowView)faresSetupBindingSource.Current)["AnCurent"].ToString() + ")?",
                            "Intrebare",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Question) == DialogResult.No)
                return;
            if (MessageBox.Show("Documentele din anul curent se vor transfera in arhiva si vor putea fi doar consultate! Continuati?",
                            "Intrebare",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Question) == DialogResult.No)
                return;
            SqlCommand cmd = null;
            MessageBox.Show("Atentie! Se vor inchide toate machetele. Salvati datele, acolo unde este cazul!",
                "Info",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);

            foreach (StudioForm fChild in MdiParent.MdiChildren)
            {
                if (fChild != this)
                    fChild.Close();
            }
            try
            {
                Cursor.Current = Cursors.AppStarting;
                cmd = new SqlCommand("InchideAnFares", DeschideConexiune(workConnString));
                cmd.CommandTimeout = 500;
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new SqlParameter("pAn", ((DataRowView)faresSetupBindingSource.Current)["AnCurent"].ToString()));
                cmd.Parameters.Add(new SqlParameter("codUnit", ModuleInfo.CodUnitate.ToString()));
                cmd.ExecuteNonQuery();

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(),
                "Eroare",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);
                return;
            }
            finally
            {
                InchideConexiune(cmd.Connection);
                Cursor.Current = Cursors.Default;
            }
            MessageBox.Show("Documentele curente au fost arhivate cu succes!",
                            "Info",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
        }

        override public void Salvare(object sender, EventArgs args)
        {
            this.SuspendLayout();
            base.Salvare(this, args);
            ResumeLayout();

            if (EroareSalvare)
                return;
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (openD394.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                caleD394TB.Text = openD394.FileName.Replace(openD394.SafeFileName, String.Empty);
            }
        }

        private void gestiuneaStocurilorCB_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            GestiuneStocuriPanel.Enabled = cb.Checked;

        }

        private void productieCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            ProductiePanel.Enabled = productieCB.Checked;
        }

        private void zileScadentaClientTextBox_Validating(object sender, CancelEventArgs e)
        {
            TextBox obj = sender as TextBox;
            if (obj != null)
            { 
                int result = 0;
                if (Int32.TryParse(obj.Text, out result))
                { 
                    if(result<=0)
                    {
                        e.Cancel = true;
                        MessageBoxFrm mbt = new MessageBoxFrm("Eroare", "Nu se accepă scadenţă la plată anticipată!", String.Empty,MessageBoxFrm.ImaginiMB.StopIcon, null);
                        mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                        mbt.ShowDialog();
                    }
                        
                }
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FrmMainMdi frm = ModuleInfo.mdiForm as FrmMainMdi;
            Assembly asm = frm.GetModule("erpforms");
            if (asm == null)
                return;

            String numeClasa = "ERPForms.JurnaleFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo, true }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;
                //newFrm.MdiParent = frm;
                newFrm.ShowDialog();
                this.jurnaleTableAdapter.Connection = DeschideConexiune(workConnString);
                this.jurnaleTableAdapter.Fill(this.eSRPDataSetSetup.Jurnale, ModuleInfo.CodUnitate);
                InchideConexiune(this.jurnaleTableAdapter.Connection);

            }

        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FrmMainMdi frm = this.MdiParent as FrmMainMdi;
            Assembly asm = frm.GetModule("exbug");
            if (asm == null)
                return;

            String numeClasa = "ExBug.ArticoleAliniateFrm";
            Type mModule = asm.GetType(numeClasa);

            if (mModule != null)
            {
                FrmRezumat newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                   new object[] { ModuleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmRezumat;

                newFrm.SelectionAddOn = true;
                newFrm.ShowDialog();
                this.articoleAliniateTableAdapter.Connection = DeschideConexiune(workConnString);
                this.articoleAliniateTableAdapter.Fill(this.eSRPDataSetSetup.ArticoleAliniate,ModuleInfo.CodUnitate);
                InchideConexiune(this.articoleAliniateTableAdapter.Connection);
                newFrm.Close();
                newFrm.Dispose();

            }
        }        
    }
}
